package com.bangdao.app.jetpacktest.jetpack.livedata;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.bangdao.app.jetpacktest.R;

/**
 * @ProjectName: JetpackTest
 * @ClassName: OneFragment
 * @Description: java类作用描述
 * @Author: luhui
 * @Email: hui.lu@bangdao-tech.com
 * @CreateDate: 2022/6/4 00:27
 * @UpdateUser: luhui
 * @UpdateDate: 2022/6/4 00:27
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class TwoFragment extends Fragment {
    private SeekBar seekBar;
    private MutableLiveData<Integer> liveData;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View parentView = inflater.inflate(R.layout.fragment_one, container, false);
        seekBar = parentView.findViewById(R.id.seekBar);

        //注意：这里ViewModelProvider(getActivity())中的参数
        //需要的是Activity，而不是Fragment，否则将接手不到监听
        ShareDataViewModel shareDataViewModel = new ViewModelProvider(this.getActivity())
                .get(ShareDataViewModel.class);

        liveData = (MutableLiveData<Integer>) shareDataViewModel.getProgress();

        //通过observe方法观察ViewModel中字段数据的变化，并在变化时得到通知
        liveData.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer progress) {
                seekBar.setProgress(progress);
            }
        });

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //当用户操作SeekBar时，更新ViewModel中的数据
                liveData.setValue(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        return parentView;
    }
}
